import type { FormInstance, FormItemProp } from "element-plus";
import { clone, storageLocal } from "@pureadmin/utils";
import { ref } from "vue";


export const useVerifyCode = (name = '') => {
  const isDisabled = ref(false);
  const timer = ref(null);
  const text = ref("");
  const endTime = ref(storageLocal().getItem(`endTime-${name}`) as number | null)
  if (endTime.value) {
    if (endTime.value > new Date().getTime()) {
      nextTick(() => {
        start(null, null, (endTime.value - new Date().getTime()) / 1000)
      })
    } else {
      storageLocal().removeItem(`endTime-${name}`)
    }
  }
  const start = async (
    formEl?: FormInstance | undefined,
    props?: FormItemProp,
    time = 60
  ) => {
    if (!formEl) {
      const initTime = clone(time, true);
      clearInterval(timer.value);
      isDisabled.value = true;
      text.value = `${Number(time + 1).toFixed(0)}`;
      timer.value = setInterval(() => {
        if (time > 0) {
          time -= 1;
          text.value = `${Number(time + 1).toFixed(0)}`;
        } else {
          text.value = "";
          isDisabled.value = false;
          clearInterval(timer.value);
          time = initTime;
        }
      }, 1000);
    } else {
      const initTime = clone(time, true);
      await formEl.validateField(props, isValid => {
        if (isValid) {
          clearInterval(timer.value);
          isDisabled.value = true;
          text.value = `${Number(time).toFixed(0)}`;
          storageLocal().setItem(`endTime-${name}`, new Date().getTime() + time * 1000)
          timer.value = setInterval(() => {
            if (time > 0) {
              time -= 1;
              text.value = `${Number(time).toFixed(0)}`;
            } else {
              text.value = "";
              isDisabled.value = false;
              clearInterval(timer.value);
              time = initTime;
            }
          }, 1000);
        }
      });
    }
  };

  const end = () => {
    text.value = "";
    isDisabled.value = false;
    clearInterval(timer.value);
  };

  return {
    isDisabled,
    timer,
    text,
    start,
    end
  };
};
